﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace ConsoleAppDemo {

    #region 错误案例，由于mutex引发异常
    public class TPoolMutex {
        /// <summary>
        /// 标记
        /// </summary>
        private static int flag = 0;
        private static Mutex mutex = new Mutex();
        /// <summary>
        /// 可执行线程最大数量
        /// </summary>
        private const int maxThreadNum = 3;
        /// <summary>
        /// 线程总量
        /// </summary>
        private const int totalThreadNum = 10;
        public static void Excute()
        {
            for (int i = 0; i < totalThreadNum; i++)
            {
                Thread t = new Thread(new ThreadStart(Run));
                t.Name = "线程" + i.ToString();
                t.Start();
            }
        }
        private static void Run()
        {
            mutex.WaitOne();
            Interlocked.Increment(ref flag);
            if (flag != maxThreadNum)
                mutex.ReleaseMutex();
            Console.WriteLine("{0}正在执行...", Thread.CurrentThread.Name);
            Thread.Sleep(5000);
            Console.WriteLine("{0}已经终止...", Thread.CurrentThread.Name);
            Interlocked.Decrement(ref flag);
        }
    } 
    #endregion
}
